package com.producerandconsumer;

public class MyStack {
    //属性
    private Object[] stack;
    private int len;        //元素个数
    private int index;        //栈顶元素指针

    public MyStack(int len) {
        this.len = len;
        //初始化栈元素
        stack = new Object[len];
        //栈顶元素归位
        this.index = 0;
    }

    //行为
    public synchronized void push(Object obj){
        if(this.index >= len){
            System.out.println("此仓库以满");

            //仓库已满，生产者线程进入等待状态
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return;
        }


        stack[this.index] = obj;
        this.index++;

        System.out.println("生产者生产了一个产品:" + getTop());
        //生产出商品，通知消费者进行消费
        this.notifyAll();
    }

    public synchronized Object pop(){
        if(this.index <= 0){
            System.out.println("此仓库为空");

            //如果仓库为空，进入等待状态，等待消费者消费
            try {
                this.wait();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return null;
        }

        Object obj = stack[--index];
        stack[index] = null;

        System.out.println("消费者消费了一个产品：" + obj);
        //消费者消费了商品，通知生产者生产
        this.notifyAll();

        return obj;
    }

    public boolean isEmpty(){
        if(this.index == 0){
            return true;
        }

        return false;
    }

    public Object getTop(){
        if(index == 0){
            return null;
        }


        return stack[index-1];
    }

}
